/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ilves;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * The class for saving and loading data for the OhTu-project Ilves.
 * @author scolphoy
 */
public class fileIO {
    private File file;

    /**
     * Creates a fileIO-instance.
     * @param filename File to use for IO-operations.
     */
    public fileIO(String filename) {
        this.file = new File(filename);
    }


    /**
     * Returns whether the file exists.
     * @return true if file exists.
     */
    public boolean exists() {
        return this.file.exists();
    }

    /**
     * Saves the given object to file specified in constructor.
     * @param o The object to save.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void write(Object o) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(this.file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(o);
            oos.flush();
            oos.close();
        fos.flush();
        fos.close();
    }

    /**
     * Reads an object from the file given to constructor.
     * @return  The first found object. null if file doesn't exist.
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Object read() throws FileNotFoundException, IOException, ClassNotFoundException {
        if (!this.exists()) return null;
        FileInputStream fis = new FileInputStream(this.file);
            ObjectInputStream ois = new ObjectInputStream(fis);
                Object o = ois.readObject();
            ois.close();
        fis.close();
        return o;
    }


}
